<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>代码调试精灵 | DeepSeek 智能助手</title>
    <style>
        :root {
            --primary: #6e48aa;
            --secondary: #9d50bb;
            --accent: #4776e6;
            --light: #f5f7fa;
            --dark: #1a1a2e;
            --success: #4caf50;
            --warning: #ff9800;
            --error: #f44336;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, var(--light), #e0e5ec);
            min-height: 100vh;
            color: var(--dark);
            overflow-x: hidden;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }
        
        header {
            text-align: center;
            margin-bottom: 2rem;
            position: relative;
        }
        
        h1 {
            font-size: 2.5rem;
            background: linear-gradient(to right, var(--primary), var(--accent));
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            margin-bottom: 0.5rem;
            animation: fadeIn 1s ease-in-out;
        }
        
        .tagline {
            font-size: 1.2rem;
            color: #666;
            margin-bottom: 1.5rem;
        }
        
        .ai-character {
            position: absolute;
            right: 0;
            top: 0;
            width: 100px;
            height: 100px;
            background: url('https://cdn-icons-png.flaticon.com/512/4712/4712035.png') no-repeat center/contain;
            filter: drop-shadow(0 0 10px rgba(110, 72, 170, 0.3));
            animation: float 3s ease-in-out infinite;
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-10px); }
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .main-panel {
            display: flex;
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        .code-editor {
            flex: 1;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            animation: slideInLeft 0.8s ease-out;
        }
        
        .editor-header {
            background: linear-gradient(to right, var(--primary), var(--secondary));
            color: white;
            padding: 0.8rem 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .editor-title {
            font-weight: bold;
        }
        
        .language-selector {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            padding: 0.3rem 0.5rem;
            border-radius: 5px;
            cursor: pointer;
        }
        
        textarea {
            width: 100%;
            height: 400px;
            padding: 1rem;
            border: none;
            resize: none;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 14px;
            line-height: 1.5;
            background: #f8f9fa;
            color: #333;
        }
        
        textarea:focus {
            outline: none;
            background: white;
        }
        
        .action-panel {
            width: 300px;
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
            animation: slideInRight 0.8s ease-out;
        }
        
        @keyframes slideInLeft {
            from { opacity: 0; transform: translateX(-50px); }
            to { opacity: 1; transform: translateX(0); }
        }
        
        @keyframes slideInRight {
            from { opacity: 0; transform: translateX(50px); }
            to { opacity: 1; transform: translateX(0); }
        }
        
        .action-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            padding: 1.5rem;
            transition: all 0.3s ease;
            cursor: pointer;
            border: 2px solid transparent;
        }
        
        .action-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            border-color: var(--primary);
        }
        
        .action-card.selected {
            border-color: var(--primary);
            background: linear-gradient(to right, rgba(110, 72, 170, 0.05), rgba(157, 80, 187, 0.05));
        }
        
        .action-icon {
            font-size: 2rem;
            margin-bottom: 0.8rem;
            color: var(--primary);
        }
        
        .action-title {
            font-weight: bold;
            margin-bottom: 0.5rem;
            color: var(--dark);
        }
        
        .action-desc {
            font-size: 0.9rem;
            color: #666;
            margin-bottom: 1rem;
        }
        
        .action-btn {
            background: linear-gradient(to right, var(--primary), var(--secondary));
            color: white;
            border: none;
            padding: 0.6rem 1rem;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            width: 100%;
            transition: all 0.3s ease;
        }
        
        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(110, 72, 170, 0.3);
        }
        
        .advanced-options {
            margin-top: 1rem;
            display: none;
        }
        
        .advanced-options.show {
            display: block;
            animation: fadeIn 0.5s ease-out;
        }
        
        .option-group {
            margin-bottom: 1rem;
        }
        
        .option-label {
            display: block;
            margin-bottom: 0.3rem;
            font-size: 0.9rem;
            color: #555;
        }
        
        .option-input {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 0.9rem;
        }
        
        .toggle-advanced {
            background: none;
            border: none;
            color: var(--primary);
            font-size: 0.8rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.3rem;
            margin-top: 0.5rem;
        }
        
        .toggle-advanced i {
            transition: transform 0.3s ease;
        }
        
        .toggle-advanced.active i {
            transform: rotate(180deg);
        }
        
        .result-panel {
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            padding: 1.5rem;
            animation: fadeIn 0.8s ease-out;
            display: none;
        }
        
        .result-panel.show {
            display: block;
        }
        
        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid #eee;
        }
        
        .result-title {
            font-weight: bold;
            color: var(--primary);
        }
        
        .copy-btn {
            background: var(--light);
            border: none;
            padding: 0.3rem 0.8rem;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.8rem;
            display: flex;
            align-items: center;
            gap: 0.3rem;
        }
        
        .copy-btn:hover {
            background: #e0e0e0;
        }
        
        .result-content {
            font-family: 'Consolas', 'Monaco', monospace;
            white-space: pre-wrap;
            line-height: 1.6;
            max-height: 300px;
            overflow-y: auto;
            padding: 0.5rem;
            background: #f8f9fa;
            border-radius: 5px;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(110, 72, 170, 0.3);
            border-radius: 50%;
            border-top-color: var(--primary);
            animation: spin 1s ease-in-out infinite;
            margin-right: 0.5rem;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .status-message {
            padding: 1rem;
            border-radius: 5px;
            margin-bottom: 1rem;
            display: none;
        }
        
        .status-message.show {
            display: block;
            animation: fadeIn 0.5s ease-out;
        }
        
        .success {
            background-color: rgba(76, 175, 80, 0.1);
            color: var(--success);
            border: 1px solid rgba(76, 175, 80, 0.3);
        }
        
        .error {
            background-color: rgba(244, 67, 54, 0.1);
            color: var(--error);
            border: 1px solid rgba(244, 67, 54, 0.3);
        }
        
        .footer {
            text-align: center;
            margin-top: 3rem;
            color: #888;
            font-size: 0.9rem;
        }
        
        @media (max-width: 768px) {
            .main-panel {
                flex-direction: column;
            }
            
            .action-panel {
                width: 100%;
                flex-direction: row;
                flex-wrap: wrap;
            }
            
            .action-card {
                width: calc(50% - 0.75rem);
            }
            
            .ai-character {
                position: static;
                margin: 0 auto 1rem;
            }
        }
        
        @media (max-width: 480px) {
            .action-card {
                width: 100%;
            }
            
            h1 {
                font-size: 2rem;
            }
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
    <div class="container">
        <header>
            <div class="ai-character"></div>
            <h1>代码调试精灵</h1>
            <p class="tagline">DeepSeek AI 驱动的智能代码助手 - 检查、优化、扩写您的代码</p>
        </header>
        
        <div class="main-panel">
            <div class="code-editor">
                <div class="editor-header">
                    <span class="editor-title">代码编辑器</span>
                    <select class="language-selector" id="language-selector">
                        <option value="javascript">JavaScript</option>
                        <option value="python">Python</option>
                        <option value="java">Java</option>
                        <option value="c++">C++</option>
                        <option value="c#">C#</option>
                        <option value="php">PHP</option>
                        <option value="ruby">Ruby</option>
                        <option value="go">Go</option>
                        <option value="swift">Swift</option>
                        <option value="typescript">TypeScript</option>
                        <option value="html">HTML</option>
                        <option value="css">CSS</option>
                        <option value="sql">SQL</option>
                    </select>
                </div>
                <textarea id="code-input" placeholder="在此输入您的代码...&#10;&#10;或者尝试粘贴以下示例代码:&#10;&#10;function calculateSum(arr) {&#10;  let sum = 0;&#10;  for (let num of arr) {&#10;    sum += num;&#10;  }&#10;  return sum;&#10;}"></textarea>
            </div>
            
            <div class="action-panel">
                <div class="action-card" id="code-review-card">
                    <div class="action-icon"><i class="fas fa-search"></i></div>
                    <h3 class="action-title">代码检查</h3>
                    <p class="action-desc">分析代码中的潜在问题，提供改进建议和最佳实践。</p>
                    <button class="action-btn" id="review-btn">检查代码</button>
                    <button class="toggle-advanced" id="toggle-review-advanced">
                        <span>高级选项</span>
                        <i class="fas fa-chevron-down"></i>
                    </button>
                    <div class="advanced-options" id="review-advanced">
                        <div class="option-group">
                            <label class="option-label">严格级别</label>
                            <select class="option-input" id="review-strictness">
                                <option value="gentle">温和</option>
                                <option value="moderate" selected>中等</option>
                                <option value="strict">严格</option>
                            </select>
                        </div>
                        <div class="option-group">
                            <label class="option-label">关注点</label>
                            <select class="option-input" id="review-focus">
                                <option value="all" selected>全部</option>
                                <option value="performance">性能</option>
                                <option value="security">安全性</option>
                                <option value="readability">可读性</option>
                                <option value="style">代码风格</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="action-card" id="code-expand-card">
                    <div class="action-icon"><i class="fas fa-expand"></i></div>
                    <h3 class="action-title">代码扩写</h3>
                    <p class="action-desc">基于现有代码扩展功能，添加注释或实现更多功能。</p>
                    <button class="action-btn" id="expand-btn">扩写代码</button>
                    <button class="toggle-advanced" id="toggle-expand-advanced">
                        <span>高级选项</span>
                        <i class="fas fa-chevron-down"></i>
                    </button>
                    <div class="advanced-options" id="expand-advanced">
                        <div class="option-group">
                            <label class="option-label">扩写方向</label>
                            <select class="option-input" id="expand-direction">
                                <option value="functional" selected>功能扩展</option>
                                <option value="optimization">性能优化</option>
                                <option value="error-handling">错误处理</option>
                                <option value="documentation">文档注释</option>
                                <option value="testing">测试用例</option>
                            </select>
                        </div>
                        <div class="option-group">
                            <label class="option-label">详细程度</label>
                            <select class="option-input" id="expand-detail">
                                <option value="concise">简洁</option>
                                <option value="balanced" selected>平衡</option>
                                <option value="detailed">详细</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="action-card" id="code-advanced-card">
                    <div class="action-icon"><i class="fas fa-magic"></i></div>
                    <h3 class="action-title">高级功能</h3>
                    <p class="action-desc">代码重构、算法优化、设计模式应用等高级操作。</p>
                    <button class="action-btn" id="advanced-btn">高级处理</button>
                    <button class="toggle-advanced" id="toggle-advanced-advanced">
                        <span>高级选项</span>
                        <i class="fas fa-chevron-down"></i>
                    </button>
                    <div class="advanced-options" id="advanced-advanced">
                        <div class="option-group">
                            <label class="option-label">操作类型</label>
                            <select class="option-input" id="advanced-operation">
                                <option value="refactor">代码重构</option>
                                <option value="optimize">算法优化</option>
                                <option value="pattern">设计模式</option>
                                <option value="convert">语言转换</option>
                                <option value="explain">详细解释</option>
                            </select>
                        </div>
                        <div class="option-group">
                            <label class="option-label">复杂度</label>
                            <select class="option-input" id="advanced-complexity">
                                <option value="basic">基础</option>
                                <option value="intermediate" selected>中级</option>
                                <option value="advanced">高级</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="status-message" id="status-message"></div>
        
        <div class="result-panel" id="result-panel">
            <div class="result-header">
                <h3 class="result-title">处理结果</h3>
                <button class="copy-btn" id="copy-result">
                    <i class="far fa-copy"></i>
                    <span>复制</span>
                </button>
            </div>
            <div class="result-content" id="result-content"></div>
        </div>
        
        <div class="footer">
            <p>代码调试精灵 v1.0 | 使用 DeepSeek API 驱动 | © 2023 AI助手团队</p>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 获取DOM元素
            const codeInput = document.getElementById('code-input');
            const languageSelector = document.getElementById('language-selector');
            const reviewBtn = document.getElementById('review-btn');
            const expandBtn = document.getElementById('expand-btn');
            const advancedBtn = document.getElementById('advanced-btn');
            const resultPanel = document.getElementById('result-panel');
            const resultContent = document.getElementById('result-content');
            const copyResultBtn = document.getElementById('copy-result');
            const statusMessage = document.getElementById('status-message');
            
            // 高级选项切换
            const toggleReviewAdvanced = document.getElementById('toggle-review-advanced');
            const reviewAdvanced = document.getElementById('review-advanced');
            const toggleExpandAdvanced = document.getElementById('toggle-expand-advanced');
            const expandAdvanced = document.getElementById('expand-advanced');
            const toggleAdvancedAdvanced = document.getElementById('toggle-advanced-advanced');
            const advancedAdvanced = document.getElementById('advanced-advanced');
            
            // 卡片选择效果
            const actionCards = document.querySelectorAll('.action-card');
            
            // 初始化
            let selectedCard = null;
            let isLoading = false;
            
            // 事件监听器
            toggleReviewAdvanced.addEventListener('click', () => toggleAdvancedOptions(reviewAdvanced, toggleReviewAdvanced));
            toggleExpandAdvanced.addEventListener('click', () => toggleAdvancedOptions(expandAdvanced, toggleExpandAdvanced));
            toggleAdvancedAdvanced.addEventListener('click', () => toggleAdvancedOptions(advancedAdvanced, toggleAdvancedAdvanced));
            
            reviewBtn.addEventListener('click', () => handleAction('review'));
            expandBtn.addEventListener('click', () => handleAction('expand'));
            advancedBtn.addEventListener('click', () => handleAction('advanced'));
            
            copyResultBtn.addEventListener('click', copyResult);
            
            actionCards.forEach(card => {
                card.addEventListener('click', function() {
                    if (selectedCard) {
                        selectedCard.classList.remove('selected');
                    }
                    this.classList.add('selected');
                    selectedCard = this;
                });
            });
            
            // 示例代码按钮
            const exampleBtn = document.createElement('button');
            exampleBtn.textContent = '加载示例代码';
            exampleBtn.style.background = 'linear-gradient(to right, var(--accent), #4776e6)';
            exampleBtn.style.color = 'white';
            exampleBtn.style.border = 'none';
            exampleBtn.style.padding = '0.5rem 1rem';
            exampleBtn.style.borderRadius = '5px';
            exampleBtn.style.cursor = 'pointer';
            exampleBtn.style.marginTop = '1rem';
            exampleBtn.style.fontSize = '0.9rem';
            exampleBtn.addEventListener('click', loadExampleCode);
            
            document.querySelector('.editor-header').appendChild(exampleBtn);
            
            // 函数定义
            function toggleAdvancedOptions(advancedDiv, toggleBtn) {
                advancedDiv.classList.toggle('show');
                toggleBtn.classList.toggle('active');
            }
            
            function handleAction(actionType) {
                const code = codeInput.value.trim();
                const language = languageSelector.value;
                
                if (!code) {
                    showStatus('请输入要处理的代码', 'error');
                    return;
                }
                
                let prompt = '';
                let options = {};
                
                switch (actionType) {
                    case 'review':
                        options = {
                            strictness: document.getElementById('review-strictness').value,
                            focus: document.getElementById('review-focus').value
                        };
                        prompt = generateReviewPrompt(code, language, options);
                        break;
                    
                    case 'expand':
                        options = {
                            direction: document.getElementById('expand-direction').value,
                            detail: document.getElementById('expand-detail').value
                        };
                        prompt = generateExpandPrompt(code, language, options);
                        break;
                    
                    case 'advanced':
                        options = {
                            operation: document.getElementById('advanced-operation').value,
                            complexity: document.getElementById('advanced-complexity').value
                        };
                        prompt = generateAdvancedPrompt(code, language, options);
                        break;
                }
                
                processCodeWithAI(prompt, actionType);
            }
            
            function generateReviewPrompt(code, language, options) {
                let prompt = `请对以下${language}代码进行代码审查和分析：\n\n${code}\n\n`;
                
                prompt += `审查要求：\n`;
                prompt += `- 严格级别：${options.strictness}\n`;
                prompt += `- 主要关注点：${options.focus}\n\n`;
                
                prompt += `请提供以下方面的反馈：\n`;
                prompt += `1. 代码中的潜在问题和错误\n`;
                prompt += `2. 性能优化建议\n`;
                prompt += `3. 安全性问题\n`;
                prompt += `4. 代码风格和可读性改进\n`;
                prompt += `5. 最佳实践建议\n\n`;
                
                prompt += `请用清晰的结构化格式返回结果，先总结主要问题，然后详细说明每个问题及改进建议。`;
                
                return prompt;
            }
            
            function generateExpandPrompt(code, language, options) {
                let prompt = `请基于以下${language}代码进行扩写：\n\n${code}\n\n`;
                
                prompt += `扩写要求：\n`;
                prompt += `- 扩写方向：${options.direction}\n`;
                prompt += `- 详细程度：${options.detail}\n\n`;
                
                switch (options.direction) {
                    case 'functional':
                        prompt += `请扩展代码的功能，添加新的相关功能或增强现有功能。`;
                        break;
                    case 'optimization':
                        prompt += `请优化代码的性能，提供更高效的实现方式。`;
                        break;
                    case 'error-handling':
                        prompt += `请添加完善的错误处理机制，考虑各种可能的异常情况。`;
                        break;
                    case 'documentation':
                        prompt += `请为代码添加详细的文档注释，包括函数说明、参数说明、返回值说明等。`;
                        break;
                    case 'testing':
                        prompt += `请为代码编写测试用例，覆盖各种使用场景和边界条件。`;
                        break;
                }
                
                prompt += `\n\n请先简要说明扩写思路，然后提供完整的扩写后代码。`;
                
                return prompt;
            }
            
            function generateAdvancedPrompt(code, language, options) {
                let prompt = `请对以下${language}代码进行高级处理：\n\n${code}\n\n`;
                
                prompt += `处理要求：\n`;
                prompt += `- 操作类型：${options.operation}\n`;
                prompt += `- 复杂度级别：${options.complexity}\n\n`;
                
                switch (options.operation) {
                    case 'refactor':
                        prompt += `请重构这段代码，改进其结构、可读性和可维护性，同时保持原有功能不变。`;
                        break;
                    case 'optimize':
                        prompt += `请优化这段代码的算法或实现方式，提高其性能或效率。`;
                        break;
                    case 'pattern':
                        prompt += `请应用适当的设计模式改进这段代码，说明使用的设计模式及其优势。`;
                        break;
                    case 'convert':
                        prompt += `请将这段代码转换为${language}语言的其他实现方式或范式。`;
                        break;
                    case 'explain':
                        prompt += `请详细解释这段代码的工作原理，包括算法、数据流和关键决策点。`;
                        break;
                }
                
                prompt += `\n\n请先说明处理思路，然后提供处理后的代码或详细解释。`;
                
                return prompt;
            }
            
            async function processCodeWithAI(prompt, actionType) {
                if (isLoading) return;
                
                isLoading = true;
                showStatus('正在处理您的代码，请稍候...', 'loading');
                resultPanel.classList.remove('show');
                
                // 模拟API调用按钮状态
                const btn = document.querySelector(`#${actionType}-btn`);
                const originalText = btn.textContent;
                btn.innerHTML = `<span class="loading"></span>处理中...`;
                btn.disabled = true;
                
                try {
                    // 这里替换为实际的DeepSeek API调用
                    // const response = await callDeepSeekAPI(prompt);
                    // const result = response.choices[0].message.content;
                    
                    // 模拟API响应
                    await new Promise(resolve => setTimeout(resolve, 2000));
                    const result = simulateAIResponse(prompt, actionType);
                    
                    showResult(result);
                    showStatus('代码处理完成！', 'success');
                } catch (error) {
                    console.error('API调用失败:', error);
                    showStatus('处理代码时出错: ' + error.message, 'error');
                } finally {
                    isLoading = false;
                    btn.textContent = originalText;
                    btn.disabled = false;
                }
            }
            
            function simulateAIResponse(prompt, actionType) {
                // 这是一个模拟函数，实际使用时应替换为真实的API调用
                const language = languageSelector.value;
                const code = codeInput.value;
                
                if (actionType === 'review') {
                    return `# 代码审查报告 (${language})
                    
                    ## 主要问题总结
                    - 发现3个潜在问题
                    - 2处性能优化机会
                    - 1个安全性注意事项
                    
                    ## 详细分析
                    
                    1. **潜在问题**
                       - 第5行: 未处理空数组情况，可能导致意外行为
                       - 第8行: 变量作用域可以优化，避免可能的污染
                       - 第12行: 缺少输入验证，可能接受非数字参数
                    
                    2. **性能优化**
                       - 考虑使用reduce方法替代for循环，更简洁高效
                       - 对于大数组，可以分批处理避免内存问题
                    
                    3. **安全性**
                       - 建议添加参数类型检查，防止非预期输入
                    
                    4. **代码风格**
                       - 函数命名符合规范
                       - 建议添加JSDoc注释
                       - 缩进和格式良好
                    
                    ## 改进建议代码
                    /**
                     * 计算数组元素的和
                     * @param {number[]} arr - 数字数组
                     * @returns {number} 数组元素的和
                     */
                    function calculateSum(arr) {
                      if (!Array.isArray(arr)) throw new Error('参数必须是数组');
                      if (arr.length === 0) return 0;
                      return arr.reduce((sum, num) => sum + num, 0);
                    }`;
                } else if (actionType === 'expand') {
                    return `# 代码扩写方案 (${language})
                    
                    ## 扩写思路
                    基于原计算数组和的函数，我们扩展以下功能：
                    - 添加输入验证
                    - 支持多种统计功能(平均值、最大值、最小值)
                    - 添加详细的文档注释
                    - 增加错误处理
                    
                    ## 扩写后代码
                    /**
                     * 计算数组的统计信息
                     * @param {number[]} arr - 数字数组
                     * @param {string} [operation='sum'] - 操作类型: 'sum', 'avg', 'max', 'min'
                     * @returns {number} 计算结果
                     * @throws {Error} 如果输入无效
                     */
                    function calculateStats(arr, operation = 'sum') {
                      // 输入验证
                      if (!Array.isArray(arr)) {
                        throw new Error('输入必须是数组');
                      }
                      
                      if (arr.length === 0) {
                        throw new Error('数组不能为空');
                      }
                      
                      const operations = ['sum', 'avg', 'max', 'min'];
                      if (!operations.includes(operation)) {
                        throw new Error('不支持的操作类型');
                      }
                      
                      // 执行计算
                      switch (operation) {
                        case 'sum':
                          return arr.reduce((acc, num) => acc + num, 0);
                        case 'avg':
                          return arr.reduce((acc, num) => acc + num, 0) / arr.length;
                        case 'max':
                          return Math.max(...arr);
                        case 'min':
                          return Math.min(...arr);
                        default:
                          return 0;
                      }
                    }
                    
                    // 示例用法
                    // console.log(calculateStats([1, 2, 3, 4], 'sum')); // 10
                    // console.log(calculateStats([1, 2, 3, 4], 'avg')); // 2.5`;
                } else if (actionType === 'advanced') {
                    return `# 高级代码处理 (${language})
                    
                    ## 重构方案
                    使用策略模式重构统计计算功能，提高扩展性和可维护性。
                    
                    ## 重构后代码
                    // 策略接口
                    class StatsStrategy {
                      calculate(arr) {
                        throw new Error('必须实现calculate方法');
                      }
                    }
                    
                    // 具体策略
                    class SumStrategy extends StatsStrategy {
                      calculate(arr) {
                        return arr.reduce((acc, num) => acc + num, 0);
                      }
                    }
                    
                    class AvgStrategy extends StatsStrategy {
                      calculate(arr) {
                        return arr.reduce((acc, num) => acc + num, 0) / arr.length;
                      }
                    }
                    
                    class MaxStrategy extends StatsStrategy {
                      calculate(arr) {
                        return Math.max(...arr);
                      }
                    }
                    
                    class MinStrategy extends StatsStrategy {
                      calculate(arr) {
                        return Math.min(...arr);
                      }
                    }
                    
                    // 上下文
                    class StatsCalculator {
                      constructor(strategy) {
                        this.strategy = strategy;
                      }
                      
                      setStrategy(strategy) {
                        this.strategy = strategy;
                      }
                      
                      calculate(arr) {
                        if (!Array.isArray(arr) {
                          throw new Error('输入必须是数组');
                        }
                        
                        if (arr.length === 0) {
                          throw new Error('数组不能为空');
                        }
                        
                        return this.strategy.calculate(arr);
                      }
                    }
                    
                    // 使用示例
                    // const calculator = new StatsCalculator(new SumStrategy());
                    // console.log(calculator.calculate([1, 2, 3, 4])); // 10
                    // calculator.setStrategy(new AvgStrategy());
                    // console.log(calculator.calculate([1, 2, 3, 4])); // 2.5
                    
                    ## 优势说明
                    - 符合开闭原则，易于扩展新统计方法
                    - 算法实现与使用解耦
                    - 运行时可以切换策略
                    - 更易于单元测试`;
                }
                
                return "AI响应模拟: " + prompt.substring(0, 200) + "...";
            }
            
            async function callDeepSeekAPI(prompt) {
                // 实际API调用函数 (需要替换为您的实现)
                const apiKey = "sk-c6a7fb0a88f04c45a858716ce9aec15c"; // 注意: 在实际应用中，不应在前端暴露API密钥
                const apiUrl = "https://api.deepseek.com/v1/chat/completions"; // 假设的API端点
                
                const response = await fetch(apiUrl, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "Authorization": `Bearer ${apiKey}`
                    },
                    body: JSON.stringify({
                        model: "deepseek-chat",
                        messages: [
                            {
                                role: "user",
                                content: prompt
                            }
                        ],
                        temperature: 0.7,
                        max_tokens: 2000
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status}`);
                }
                
                return await response.json();
            }
            
            function showResult(content) {
                resultContent.textContent = content;
                resultPanel.classList.add('show');
                resultPanel.scrollIntoView({ behavior: 'smooth' });
            }
            
            function showStatus(message, type) {
                statusMessage.textContent = message;
                statusMessage.className = 'status-message show ' + type;
                
                if (type !== 'loading') {
                    setTimeout(() => {
                        statusMessage.classList.remove('show');
                    }, 5000);
                }
            }
            
            function copyResult() {
                navigator.clipboard.writeText(resultContent.textContent)
                    .then(() => {
                        const originalText = copyResultBtn.querySelector('span').textContent;
                        copyResultBtn.querySelector('span').textContent = '已复制!';
                        setTimeout(() => {
                            copyResultBtn.querySelector('span').textContent = originalText;
                        }, 2000);
                    })
                    .catch(err => {
                        console.error('复制失败:', err);
                    });
            }
            
            function loadExampleCode() {
                const language = languageSelector.value;
                let exampleCode = '';
                
                switch (language) {
                    case 'javascript':
                        exampleCode = `function findPrimes(limit) {
  const primes = [];
  for (let num = 2; num <= limit; num++) {
    let isPrime = true;
    for (let i = 2; i <= Math.sqrt(num); i++) {
      if (num % i === 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) primes.push(num);
  }
  return primes;
}`;
                        break;
                    
                    case 'python':
                        exampleCode = `def find_primes(limit):
    primes = []
    for num in range(2, limit + 1):
        is_prime = True
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(num)
    return primes`;
                        break;
                    
                    case 'java':
                        exampleCode = `import java.util.ArrayList;
import java.util.List;

public class PrimeFinder {
    public static List<Integer> findPrimes(int limit) {
        List<Integer> primes = new ArrayList<>();
        for (int num = 2; num <= limit; num++) {
            boolean isPrime = true;
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) primes.add(num);
        }
        return primes;
    }
}`;
                        break;
                    
                    default:
                        exampleCode = `// ${language}示例代码\n// 请选择特定语言查看相关示例`;
                }
                
                codeInput.value = exampleCode;
                showStatus(`已加载${language}示例代码`, 'success');
            }
        });
    </script>
</body>
</html>